﻿using System;
using System.IO;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.ResourceManagement.Workflow.Activities;
using Microsoft.ResourceManagement.WebServices.WSResourceManagement;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
//using FIM.Extensions.Common.Library;
using FIM.PS.Resources;
using System.Security;
using System.Runtime.InteropServices; // DllImport
//using System.Security.Principal; // WindowsImpersonationContext
//using System.Security.Permissions; // PermissionSetAttribute
using System.Reflection;

namespace FIMActivitiesLibrary
{
    public partial class PowershellActivity : SequenceActivity
    {

        public PowershellActivity()
        {
            InitializeComponent();
        }

        #region Regular Expressions
        Regex guidRegEx = new Regex("^*[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}", RegexOptions.CultureInvariant);
        Regex optionalXpathRegEx = new Regex(@"\A(?<attributes>.*)\s(?<xpath>/.*)", RegexOptions.CultureInvariant);
        Regex parameterRegEx = new Regex(@"\A(?<parameterName>.*)\s(?<command>\x5B//(?<parameterBase>[a-öA-Ö0-9]*)/(?<parameterAttribute>[a-öA-Ö0-9]*)])\s?(?<optionalText>.*)\r?", RegexOptions.CultureInvariant);
        Regex parameterLinesRegEx = new Regex(@"(?<parameterName>.*)\s(?<command>\x5B//(?<parameterBase>[a-öA-Ö0-9]*)/(?<parameterAttribute>[a-öA-Ö0-9]*)])\s?(?<optionalText>.*)", RegexOptions.CultureInvariant);
        Regex commandRegEx = new Regex(@"(?<command>\x5B//(?<parameterBase>[a-öA-Ö0-9]*)/(?<parameterAttribute>[a-öA-Ö0-9]*)])", RegexOptions.CultureInvariant);
        #endregion

        #region readResourceActivity

        public static DependencyProperty readResourceActivity1_ActorId1Property = DependencyProperty.Register("readResourceActivity1_ActorId1", typeof(System.Guid), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Parameters")]
        public Guid readResourceActivity1_ActorId1
        {
            get
            {
                return ((System.Guid)(base.GetValue(FIMActivitiesLibrary.PowershellActivity.readResourceActivity1_ActorId1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.readResourceActivity1_ActorId1Property, value);
            }
        }

        public static DependencyProperty readResourceActivity1_Resource1Property = DependencyProperty.Register("readResourceActivity1_Resource1", typeof(Microsoft.ResourceManagement.WebServices.WSResourceManagement.ResourceType), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Parameters")]
        public Microsoft.ResourceManagement.WebServices.WSResourceManagement.ResourceType readResourceActivity1_Resource1
        {
            get
            {
                return ((Microsoft.ResourceManagement.WebServices.WSResourceManagement.ResourceType)(base.GetValue(FIMActivitiesLibrary.PowershellActivity.readResourceActivity1_Resource1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.readResourceActivity1_Resource1Property, value);
            }
        }

        public static DependencyProperty readResourceActivity1_ResourceId1Property = DependencyProperty.Register("readResourceActivity1_ResourceId1", typeof(System.Guid), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Parameters")]
        public Guid readResourceActivity1_ResourceId1
        {
            get
            {
                return ((System.Guid)(base.GetValue(FIMActivitiesLibrary.PowershellActivity.readResourceActivity1_ResourceId1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.readResourceActivity1_ResourceId1Property, value);
            }
        }

        public static DependencyProperty readResourceActivity1_SelectionAttributes1Property = DependencyProperty.Register("readResourceActivity1_SelectionAttributes1", typeof(System.String[]), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Parameters")]
        public String[] readResourceActivity1_SelectionAttributes1
        {
            get
            {
                return ((string[])(base.GetValue(FIMActivitiesLibrary.PowershellActivity.readResourceActivity1_SelectionAttributes1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.readResourceActivity1_SelectionAttributes1Property, value);
            }
        }
        #endregion

        #region updateResourceActivity
        public static DependencyProperty updateResourceActivity1_ActorId1Property = DependencyProperty.Register("updateResourceActivity1_ActorId1", typeof(System.Guid), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Parameters")]
        public Guid updateResourceActivity1_ActorId1
        {
            get
            {
                return ((System.Guid)(base.GetValue(FIMActivitiesLibrary.PowershellActivity.updateResourceActivity1_ActorId1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.updateResourceActivity1_ActorId1Property, value);
            }
        }

        public static DependencyProperty updateResourceActivity1_ApplyAuthorizationPolicy1Property = DependencyProperty.Register("updateResourceActivity1_ApplyAuthorizationPolicy1", typeof(System.Boolean), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Parameters")]
        public Boolean updateResourceActivity1_ApplyAuthorizationPolicy1
        {
            get
            {
                return ((bool)(base.GetValue(FIMActivitiesLibrary.PowershellActivity.updateResourceActivity1_ApplyAuthorizationPolicy1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.updateResourceActivity1_ApplyAuthorizationPolicy1Property, value);
            }
        }

        public static DependencyProperty updateResourceActivity1_ResourceId1Property = DependencyProperty.Register("updateResourceActivity1_ResourceId1", typeof(System.Guid), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Parameters")]
        public Guid updateResourceActivity1_ResourceId1
        {
            get
            {
                return ((System.Guid)(base.GetValue(FIMActivitiesLibrary.PowershellActivity.updateResourceActivity1_ResourceId1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.updateResourceActivity1_ResourceId1Property, value);
            }
        }

        public static DependencyProperty updateResourceActivity1_UpdateParameters1Property = DependencyProperty.Register("updateResourceActivity1_UpdateParameters1", typeof(Microsoft.ResourceManagement.WebServices.WSResourceManagement.UpdateRequestParameter[]), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Parameters")]
        public UpdateRequestParameter[] updateResourceActivity1_UpdateParameters1
        {
            get
            {
                return ((Microsoft.ResourceManagement.WebServices.WSResourceManagement.UpdateRequestParameter[])(base.GetValue(FIMActivitiesLibrary.PowershellActivity.updateResourceActivity1_UpdateParameters1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.updateResourceActivity1_UpdateParameters1Property, value);
            }
        }
        #endregion

        #region currentRequestActivity DeendencyProperty

        public static DependencyProperty currentRequestActivity1_CurrentRequest1Property = DependencyProperty.Register("currentRequestActivity1_CurrentRequest1", typeof(Microsoft.ResourceManagement.WebServices.WSResourceManagement.RequestType), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Misc")]
        public Microsoft.ResourceManagement.WebServices.WSResourceManagement.RequestType currentRequestActivity1_CurrentRequest1
        {
            get
            {
                return ((Microsoft.ResourceManagement.WebServices.WSResourceManagement.RequestType)(base.GetValue(FIMActivitiesLibrary.PowershellActivity.currentRequestActivity1_CurrentRequest1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.currentRequestActivity1_CurrentRequest1Property, value);
            }
        }

        #endregion

        //Usage:
        //All dependency properties used with ActivitySettingsPart
        #region ActivitySettingsParts DependencyProperties

        public static DependencyProperty PSCredentialUserNameProperty = DependencyProperty.Register("PSCredentialUserName", typeof(string), typeof(PowershellActivity));

        [Description("PSCredentialUserName")]
        [Category("PSCredentialUserName Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string PSCredentialUserName
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.PSCredentialUserNameProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.PSCredentialUserNameProperty, value);
            }
        }

        public static DependencyProperty PSCredentialPasswordProperty = DependencyProperty.Register("PSCredentialPassword", typeof(string), typeof(PowershellActivity));

        [Description("PSCredentialPassword")]
        [Category("PSCredentialPassword Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string PSCredentialPassword
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.PSCredentialPasswordProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.PSCredentialPasswordProperty, value);
            }
        }

        //public static DependencyProperty ExecutionModeProperty = DependencyProperty.Register("ExecutionMode", typeof(string), typeof(PowershellActivity));

        //[Description("ExecutionMode")]
        //[Category("ExecutionMode Category")]
        //[Browsable(true)]
        //[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        //public string ExecutionMode
        //{
        //    get
        //    {
        //        return ((string)(base.GetValue(PowershellActivity.ExecutionModeProperty)));
        //    }
        //    set
        //    {
        //        base.SetValue(PowershellActivity.ExecutionModeProperty, value);
        //    }
        //}

        public static DependencyProperty AuthenticationMechanismProperty = DependencyProperty.Register("AuthenticationMechanism", typeof(string), typeof(PowershellActivity));

        [Description("AuthenticationMechanism")]
        [Category("AuthenticationMechanism Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string AuthenticationMechanism
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.AuthenticationMechanismProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.AuthenticationMechanismProperty, value);
            }
        }

        public static DependencyProperty powershellCmdLetPluginsProperty = DependencyProperty.Register("powershellCmdLetPlugins", typeof(string), typeof(PowershellActivity));

        [Description("powershellCmdLetPlugins")]
        [Category("powershellCmdLetPlugins Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string powershellCmdLetPlugins
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.powershellCmdLetPluginsProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.powershellCmdLetPluginsProperty, value);
            }
        }

        public static DependencyProperty enableActivityProperty = DependencyProperty.Register("enableActivity", typeof(bool), typeof(PowershellActivity));

        [Description("enableActivity")]
        [Category("enableActivity Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public bool enableActivity
        {
            get
            {
                return ((bool)(base.GetValue(PowershellActivity.enableActivityProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.enableActivityProperty, value);
            }
        }

        public static DependencyProperty activityNameProperty = DependencyProperty.Register("activityName", typeof(string), typeof(PowershellActivity));

        [Description("activityName")]
        [Category("activityName Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string activityName
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.activityNameProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.activityNameProperty, value);
            }
        }
        public static DependencyProperty powershellParametersProperty = DependencyProperty.Register("powershellParameters", typeof(string), typeof(PowershellActivity));

        [Description("powershellParameters")]
        [Category("powershellParameters Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string powershellParameters
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.powershellParametersProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.powershellParametersProperty, value);
            }
        }

        public static DependencyProperty targetUpdateParametersProperty = DependencyProperty.Register("targetUpdateParameters", typeof(string), typeof(PowershellActivity));

        [Description("targetUpdateParameters")]
        [Category("targetUpdateParameters Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string targetUpdateParameters
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.targetUpdateParametersProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.targetUpdateParametersProperty, value);
            }
        }

        public static DependencyProperty ReadTargetActorIDProperty = DependencyProperty.Register("ReadTargetActorID", typeof(string), typeof(PowershellActivity));

        [Description("ReadTargetActorID")]
        [Category("ReadTargetActorID Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string ReadTargetActorID
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.ReadTargetActorIDProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.ReadTargetActorIDProperty, value);
            }
        }

        public static DependencyProperty ActorID_UpdateProperty = DependencyProperty.Register("ActorID_Update", typeof(string), typeof(PowershellActivity));

        [Description("ActorID_Update")]
        [Category("ActorID_Update Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string ActorID_Update
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.ActorID_UpdateProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.ActorID_UpdateProperty, value);
            }
        }

        public static DependencyProperty PowershellCmdLetScriptProperty = DependencyProperty.Register("PowershellCmdLetScript", typeof(string), typeof(PowershellActivity));

        [Description("PowershellCmdLetScript")]
        [Category("PowershellCmdLetScript Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string PowershellCmdLetScript
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.PowershellCmdLetScriptProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.PowershellCmdLetScriptProperty, value);
            }
        }

        public static DependencyProperty RemoteServerProperty = DependencyProperty.Register("RemoteServer", typeof(string), typeof(PowershellActivity));

        [Description("RemoteServer")]
        [Category("RemoteServer Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string RemoteServer
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.RemoteServerProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.RemoteServerProperty, value);
            }
        }

        public static DependencyProperty UserNameProperty = DependencyProperty.Register("UserName", typeof(string), typeof(PowershellActivity));

        [Description("UserName")]
        [Category("UserName Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string UserName
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.UserNameProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.UserNameProperty, value);
            }
        }

        public static DependencyProperty UserPasswordProperty = DependencyProperty.Register("UserPassword", typeof(string), typeof(PowershellActivity));

        [Description("UserPassword")]
        [Category("UserPassword Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string UserPassword
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.UserPasswordProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.UserPasswordProperty, value);
            }
        }

        public static DependencyProperty readTargetResourceIdParameterProperty = DependencyProperty.Register("readTargetResourceIdParameter", typeof(string), typeof(PowershellActivity));

        [Description("readTargetResourceIdParameter")]
        [Category("readTargetResourceIdParameter Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string readTargetResourceIdParameter
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.readTargetResourceIdParameterProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.readTargetResourceIdParameterProperty, value);
            }
        }

        public static DependencyProperty updateTargetResourceIdParameterProperty = DependencyProperty.Register("updateTargetResourceIdParameter", typeof(string), typeof(PowershellActivity));

        [Description("updateTargetResourceIdParameter")]
        [Category("updateTargetResourceIdParameter Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string updateTargetResourceIdParameter
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.updateTargetResourceIdParameterProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.updateTargetResourceIdParameterProperty, value);
            }
        }

        public static DependencyProperty loggingLevelProperty = DependencyProperty.Register("loggingLevel", typeof(int), typeof(PowershellActivity));

        [Description("loggingLevel")]
        [Category("loggingLevel Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public int loggingLevel
        {
            get
            {
                return ((int)(base.GetValue(PowershellActivity.loggingLevelProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.loggingLevelProperty, value);
            }
        }

        public static DependencyProperty eventLogNameProperty = DependencyProperty.Register("eventLogName", typeof(String), typeof(PowershellActivity));

        [Description("eventLogName")]
        [Category("eventLogName Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string eventLogName
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.eventLogNameProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.eventLogNameProperty, value);
            }
        }

        #endregion

        #region Shared DepencencyProperties

        public static DependencyProperty updateTargetActorIDProperty = DependencyProperty.Register("updateTargetActorID", typeof(Guid), typeof(PowershellActivity));

        [Description("updateTargetActorID")]
        [Category("updateTargetActorID Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public Guid updateTargetActorID
        {
            get
            {
                return ((Guid)(base.GetValue(PowershellActivity.updateTargetActorIDProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.updateTargetActorIDProperty, value);
            }
        }

        public static DependencyProperty myUpdateRequestParametersProperty = DependencyProperty.Register("myUpdateRequestParameters", typeof(List<UpdateRequestParameter>), typeof(PowershellActivity));

        [Description("myUpdateRequestParameters")]
        [Category("myUpdateRequestParameters Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public List<UpdateRequestParameter> myUpdateRequestParameters
        {
            get
            {
                return ((List<UpdateRequestParameter>)(base.GetValue(PowershellActivity.myUpdateRequestParametersProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.myUpdateRequestParametersProperty, value);
            }
        }

        public static DependencyProperty EnumeratedResourcesProperty = DependencyProperty.Register("EnumeratedResources", typeof(List<ResourceType>), typeof(PowershellActivity));

        [Description("EnumeratedResource")]
        [Category("Result")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public List<ResourceType> EnumeratedResources
        {
            get { return (List<ResourceType>)base.GetValue(PowershellActivity.EnumeratedResourcesProperty); }
            set { base.SetValue(PowershellActivity.EnumeratedResourcesProperty, value); }
        }

        public static DependencyProperty updateTargetResourcesIDProperty = DependencyProperty.Register("updateTargetResourcesID", typeof(ArrayList), typeof(PowershellActivity));

        [Description("updateTargetResourcesID")]
        [Category("updateTargetResourcesID Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public ArrayList updateTargetResourcesID
        {
            get
            {
                return ((ArrayList)(base.GetValue(PowershellActivity.updateTargetResourcesIDProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.updateTargetResourcesIDProperty, value);
            }
        }

        //Usage: Determins if properties from target resource needs to to be fetched.
        public static DependencyProperty executeReadTargetResourceProperty = DependencyProperty.Register("executeReadTargetResource", typeof(bool), typeof(PowershellActivity));
        [Description("executeReadTargetResource")]
        [Category("executeReadTargetResource Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public bool executeReadTargetResource
        {
            get
            {
                return ((bool)(base.GetValue(PowershellActivity.executeReadTargetResourceProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.executeReadTargetResourceProperty, value);
            }
        }

        //Usage: Stores the result from powershell execution
        public static DependencyProperty resultHashTableProperty = DependencyProperty.Register("resultHashTable", typeof(Hashtable), typeof(PowershellActivity));
        [Description("resultHashTable")]
        [Category("resultHashTable Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public Hashtable resultHashTable
        {
            get
            {
                return ((Hashtable)(base.GetValue(PowershellActivity.resultHashTableProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.resultHashTableProperty, value);
            }
        }

        //Usage: Stores the runspace for executing powershell
        public static DependencyProperty powershellRunSpaceProperty = DependencyProperty.Register("powershellRunSpace", typeof(Runspace), typeof(PowershellActivity));
        [Description("powershellRunSpace")]
        [Category("powershellRunSpace Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public Runspace powershellRunSpace
        {
            get
            {
                return ((Runspace)(base.GetValue(PowershellActivity.powershellRunSpaceProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.powershellRunSpaceProperty, value);
            }
        }

        //Usage: Stores the powershell script to be executed
        public static DependencyProperty executePowershellScriptProperty = DependencyProperty.Register("executePowershellScript", typeof(string), typeof(PowershellActivity));
        [Description("executePowershellScript")]
        [Category("executePowershellScript Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string executePowershellScript
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.executePowershellScriptProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.executePowershellScriptProperty, value);
            }
        }

        //Usage: Stores the start time of an activity
        public static DependencyProperty ActionStartTimeProperty = DependencyProperty.Register("ActionStartTime", typeof(DateTime), typeof(PowershellActivity));
        [Description("ActionStartTime")]
        [Category("ActionStartTime Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public DateTime ActionStartTime
        {
            get
            {
                return ((DateTime)(base.GetValue(PowershellActivity.ActionStartTimeProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.ActionStartTimeProperty, value);
            }
        }

        //Usage: Stores the workflow start time
        public static DependencyProperty workFlowStartTimeProperty = DependencyProperty.Register("workFlowStartTime", typeof(DateTime), typeof(PowershellActivity));
        [Description("workFlowStartTime")]
        [Category("workFlowStartTime Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public DateTime workFlowStartTime
        {
            get
            {
                return ((DateTime)(base.GetValue(PowershellActivity.workFlowStartTimeProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.workFlowStartTimeProperty, value);
            }
        }

        //Stores the message for the eventlog, is updated by all activities in this workflow
        public static DependencyProperty eventLogMessageProperty = DependencyProperty.Register("eventLogMessage", typeof(string), typeof(PowershellActivity));
        [Description("eventLogMessage")]
        [Category("eventLogMessage Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string eventLogMessage
        {
            get
            {
                return ((string)(base.GetValue(PowershellActivity.eventLogMessageProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.eventLogMessageProperty, value);
            }
        }

        //Usage: Stores all attributes and values to be used when resolving parameters before executing powershell
        public static DependencyProperty requestDictionaryProperty = DependencyProperty.Register("requestDictionary", typeof(Dictionary<String, ArrayList>), typeof(PowershellActivity));
        [Description("requestDictionary")]
        [Category("requestDictionary Category")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public Dictionary<String, ArrayList> requestDictionary
        {
            get
            {
                return ((Dictionary<String, ArrayList>)(base.GetValue(PowershellActivity.requestDictionaryProperty)));
            }
            set
            {
                base.SetValue(PowershellActivity.requestDictionaryProperty, value);
            }
        }

        public static DependencyProperty faultHandlerActivity2_Fault1Property = DependencyProperty.Register("faultHandlerActivity2_Fault1", typeof(System.Exception), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Misc")]
        public Exception faultHandlerActivity2_Fault1
        {
            get
            {
                return ((System.Exception)(base.GetValue(FIMActivitiesLibrary.PowershellActivity.faultHandlerActivity2_Fault1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.faultHandlerActivity2_Fault1Property, value);
            }
        }

        public static DependencyProperty updateResourceActivity1_AuthorizationWaitTimeInSeconds1Property = DependencyProperty.Register("updateResourceActivity1_AuthorizationWaitTimeInSeconds1", typeof(System.Int32), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Parameters")]
        public Int32 updateResourceActivity1_AuthorizationWaitTimeInSeconds1
        {
            get
            {
                return ((int)(base.GetValue(FIMActivitiesLibrary.PowershellActivity.updateResourceActivity1_AuthorizationWaitTimeInSeconds1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.updateResourceActivity1_AuthorizationWaitTimeInSeconds1Property, value);
            }
        }

        public static DependencyProperty ReadResourceFaultHandlerActivity1_Fault1Property = DependencyProperty.Register("ReadResourceFaultHandlerActivity1_Fault1", typeof(System.Exception), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Misc")]
        public Exception ReadResourceFaultHandlerActivity1_Fault1
        {
            get
            {
                return ((System.Exception)(base.GetValue(FIMActivitiesLibrary.PowershellActivity.ReadResourceFaultHandlerActivity1_Fault1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.ReadResourceFaultHandlerActivity1_Fault1Property, value);
            }
        }

        public static DependencyProperty faultHandlerActivity1_Fault1Property = DependencyProperty.Register("faultHandlerActivity1_Fault1", typeof(System.Exception), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Misc")]
        public Exception faultHandlerActivity1_Fault1
        {
            get
            {
                return ((System.Exception)(base.GetValue(FIMActivitiesLibrary.PowershellActivity.faultHandlerActivity1_Fault1Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.faultHandlerActivity1_Fault1Property, value);
            }
        }

        #endregion

        #region faultDependencyProperties
        public static DependencyProperty faultHandlerActivity1_Fault2Property = DependencyProperty.Register("faultHandlerActivity1_Fault2", typeof(System.Exception), typeof(FIMActivitiesLibrary.PowershellActivity));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Misc")]
        public Exception faultHandlerActivity1_Fault2
        {
            get
            {
                return ((System.Exception)(base.GetValue(FIMActivitiesLibrary.PowershellActivity.faultHandlerActivity1_Fault2Property)));
            }
            set
            {
                base.SetValue(FIMActivitiesLibrary.PowershellActivity.faultHandlerActivity1_Fault2Property, value);
            }
        }
        #endregion

        Assembly assembly = Assembly.GetExecutingAssembly();
        static string eventLogSource = Assembly.GetExecutingAssembly().GetName().Name;

        #region Common Functions
        //Usage: Trim CR and LF from end of string
        public static String trimCRLF(string input)
        {
            if (String.IsNullOrEmpty(input)) return null;
            String result = input;
            if (result.Contains("\n")) result = result.Remove(result.LastIndexOf("\n"));
            if (result.Contains("\r")) result = result.Remove(result.LastIndexOf("\r"));
            return result;
        }

        //Usage: Add text to eventlogmessage depending on current logging level
        public void AddEventLogMessage(String messageText, int requiredLogLevel)
        {
            if (this.loggingLevel >= requiredLogLevel && !string.IsNullOrEmpty(messageText))
                this.eventLogMessage += messageText + Environment.NewLine;
        }

        //Usage: Updates the requestDictionary dependency property adds new if not exists or update existing keys 
        //
        //Input: Key = name of the attribute to add/update
        //       value = value of the attribute
        //
        //Output: resultDictionary dependency property
        //
        private void UpdateDictionary(String key, String value)
        {
            //Replace all urn on reference attributes
            if (!String.IsNullOrEmpty(value) && value.Contains("urn:uuid:")) { value = value.Replace("urn:uuid:", ""); }
            Dictionary<string, System.Collections.ArrayList> requestDictionaryIgnoreCase = new Dictionary<string, System.Collections.ArrayList>(StringComparer.InvariantCultureIgnoreCase);
            try
            {
                ArrayList myArrayList = new ArrayList();

                if (!this.requestDictionary.ContainsKey(key))
                {
                    myArrayList.Add(value);
                    this.requestDictionary.Add(key, myArrayList);
                }
                else
                {
                    this.requestDictionary.TryGetValue(key, out myArrayList);
                    this.requestDictionary.Remove(key);
                    myArrayList.Add(value);
                    this.requestDictionary.Add(key, myArrayList);

                }
            }
            catch (Exception ex)
            {
                AddEventLogMessage("#Error, Failed to update request dictionary : " + ex.Message, 1);
            }
        }

        //Usage: Resolve a parameter from the requestDictionary
        //
        //Input: unresolvedParameter = [//xxx/yyy] where xxx is type and yyy is attribute
        //       Example: [//target/FirstName], [//credential/user]
        //  
        //       requestDictionary that contains all request parameters and values
        //
        //Output: ArrayList of all values
        //
        private ArrayList ResolveRequestParameter(String unresolvedParameter)
        {
            ArrayList values = new ArrayList();

            //Try to find a resolved value from request parameters
            try
            {
                AddEventLogMessage("- Search for unresolved parameter : " + unresolvedParameter, 4);

                if (this.requestDictionary.TryGetValue(unresolvedParameter, out values))
                {
                    if ((values != null) && (values.Count > 0))
                    {
                        AddEventLogMessage("- Resolved '" + unresolvedParameter + "' value(s) from request parameters", 3);
                        if (loggingLevel >= 3)
                            foreach (String item in values) { AddEventLogMessage(" '" + item + "'", 3); }
                    }
                }
                else
                {
                    AddEventLogMessage("[Warning] No values was resolved from '" + unresolvedParameter + "' request parameters", 3);
                }

                return values;
            }
            catch (Exception ex) { AddEventLogMessage("Error, Failed to resolve request dictionary : " + ex.Message, 1); }

            AddEventLogMessage("[Warning] Unable to resolve '" + unresolvedParameter + "' from request parameters", 2);
            return null;
        }

        //Validate if textline is not commented or blank, used to exlude lines not to be resolvedor used inconfiguration.
        public bool IsValidTextLine(String text)
        {
            if (String.IsNullOrEmpty(text)) { return false; }
            if (text.StartsWith("'") || text.StartsWith(";") || text.StartsWith("#") || text.StartsWith("//"))
            { return false; }
            return true;
        }

        //Usage: Resolve UnresolvedID to a target guid used to select target object
        //       Resolves the target inthe following order {Specified GUID}, {From Request parameters}, {From Result Parameters}
        //
        //Input: An uresolved parameter with the format [//xxx/yyy]
        //
        //Output: GuidRef   - The guid of the resolved resource
        //
        private Guid ResolveActorTargetID(String actorTargetIdParameter, Guid currentActorTargetID)
        {
            String resolvedGuid = null;
            ArrayList guidArray = new ArrayList();

            if (!IsValidTextLine(actorTargetIdParameter))
            {
                AddEventLogMessage(" [Information], Invalid or empty value '" + actorTargetIdParameter + "', defaulting to current : " + currentActorTargetID.ToString(), 3);
                return currentActorTargetID;
            }

            //Check if specific guid is specified
            resolvedGuid = this.guidRegEx.Match(actorTargetIdParameter).Value.ToString();
            if (!String.IsNullOrEmpty(resolvedGuid))
            {
                AddEventLogMessage(" Specified by GUID : " + resolvedGuid, 3);
                return new Guid(resolvedGuid);
            }

            //Try resolve from request parameters
            guidArray = ResolveRequestParameter(actorTargetIdParameter);
            if (guidArray != null && guidArray.Count > 0)
            {
                String resultGuid = this.guidRegEx.Match(guidArray[0].ToString()).Value.ToString();
                AddEventLogMessage(" Specified by parameter : " + actorTargetIdParameter, 3);
                return new Guid(resultGuid);
            }

            AddEventLogMessage(" [Warning] Unable to resolve '" + actorTargetIdParameter + "', defaulting to current : " + currentActorTargetID.ToString(), 3);
            return currentActorTargetID;

        }

        #endregion

        //Function: Initilizes the workflow by setting starttime and add some information to eventlog message
        private void InitWorkflowActivity_ExecuteCode(object sender, EventArgs e)
        {
            this.workFlowStartTime = DateTime.Now;
            this.eventLogMessage = "";

            this.requestDictionary = new Dictionary<string, ArrayList>();

            AddEventLogMessage("[Workflow configuration information]", 1);
            AddEventLogMessage("Powershell Activity Name : " + this.activityName, 1);
            AddEventLogMessage("Powershell Assembly Information : " + Assembly.GetExecutingAssembly().FullName, 1);
            AddEventLogMessage("Logging level : " + this.loggingLevel.ToString(), 1);
            AddEventLogMessage("Activity enabled : " + this.enableActivity.ToString(), 1);
#if DEBUG
            AddEventLogMessage("[Warning], Running in debug mode, performance will be affected ", 0);
#endif
            AddEventLogMessage(Environment.NewLine + "[Configured powershell parameters]", 2);
            if (String.IsNullOrEmpty(powershellParameters)) { AddEventLogMessage("[Warning], No powershell parameters is configured", 2); }
            else { AddEventLogMessage(this.powershellParameters, 2); }
            AddEventLogMessage(Environment.NewLine + "[Configured Update Target Parameters]", 2);
            if (String.IsNullOrEmpty(targetUpdateParameters)) { AddEventLogMessage("[Information], No update target parameters is configured", 2); }
            else { AddEventLogMessage(targetUpdateParameters, 2); }
        }

        //Function: Add all existing WorkflowData attributes and values into requestDictionary property
        //
        //Output:   requestDictionary - Format :[//WorkFlowData/{attribute}]
        private void initReadWorkflowData_ExecuteCode(object sender, EventArgs e)
        {
            AddEventLogMessage(Environment.NewLine + "[Read WorkflowData from current request]", 1);

            // In order to read the Workflow Dictionary we need to get the containing (parent) workflow
            SequentialWorkflow containingWorkflow = null;
            if (!SequentialWorkflow.TryGetContainingWorkflow(this, out containingWorkflow))
                throw new InvalidOperationException("Could not get parent workflow!");

            if (containingWorkflow.WorkflowDictionary.Count > 0)
            {
                AddEventLogMessage("- Found " + containingWorkflow.WorkflowDictionary.Count.ToString() + " WorkFlowData entrys to fetch", 1);
                foreach (KeyValuePair<String, object> item in containingWorkflow.WorkflowDictionary)
                {
                    ArrayList myValues = new ArrayList();
                    if (item.Value is Array) myValues.AddRange((Object[])item.Value);
                    else if (item.Value is ArrayList) myValues.AddRange((ArrayList)item.Value);
                    else myValues.Add(item.Value);

                    foreach (Object value in myValues)
                    {
                        AddEventLogMessage("- Add requestParameter [//WorkflowData/" + item.Key.ToString() + "] = " + value.ToString(), 2);
                        UpdateDictionary("[//WorkflowData/" + item.Key.ToString() + "]", value.ToString());
                    }
                }
            }
            else AddEventLogMessage("- No WorkFlowData found in the request", 2);

            if (currentRequestActivity1_CurrentRequest1.Operation != OperationType.Delete) executeReadTargetResource = true; else executeReadTargetResource = false;
        }

        //Function: Initialize the readresourceactivity by populate attributes to read from target resource
        //          Takes input from the powershell parameters on activitysettingspart and enumerate and resolve all [//xxx/yyy]
        //          xxx = type of modification    {target|targetmodify}
        //          yyy = name of attribute       {FirstName}
        //
        //Input:
        //
        //Output:
        //
        private void initReadResource_ExecuteCode(object sender, EventArgs e)
        {

            //regExUtils myRegExUtils = new regExUtils();

            SequentialWorkflow containingWorkflow = null;
            if (!SequentialWorkflow.TryGetContainingWorkflow(this, out containingWorkflow))
            { throw new InvalidProgramException(); }

            AddEventLogMessage(Environment.NewLine + "[Init Read Resource]", 2);

            //Resolve targetID from workflow
            //This will be used to switch from witch target to read from when resolving powershell parameters [//Target/attributename]
            //If not resolved or empty the default resource from current request is used
            AddEventLogMessage("- Resolve Target ResourceID", 3);
            this.readResourceActivity1_ResourceId1 = containingWorkflow.TargetId;
            Guid resourceID = this.readResourceActivity1_ResourceId1;
            resourceID = ResolveActorTargetID(readTargetResourceIdParameter, resourceID);
            readResourceActivity1_ResourceId1 = resourceID;

            //Resolve the ActorID from PSActorID specified in the ActivitySettings
            //This will switch the actorID to execute the read target asforexample to elevate the permission
            //If not resolved or empty the default actorID from current request is used
            AddEventLogMessage("- Resolve ActorID", 3);
            this.readResourceActivity1_ActorId1 = containingWorkflow.ActorId;
            Guid actorID = this.readResourceActivity1_ActorId1;
            actorID = ResolveActorTargetID(ReadTargetActorID, actorID);
            readResourceActivity1_ActorId1 = actorID;

            //Populate attributes to read from target from parameters
            List<String> targetSearchAttributes = new List<String>();
            String searchParameters = this.powershellParameters;

            AddEventLogMessage("- Get all [//Target/*] from configuration", 1);

            //If update ActorID is defined as a target attribute include this parameter in the list to read from target
            if (ActorID_Update.ToLower().StartsWith("[//target/")) { searchParameters += Environment.NewLine + ActorID_Update; }

            //Add updateTargetResourceIdParameter to seaarch
            if (updateTargetResourceIdParameter.Contains("[//target/")) { searchParameters += updateTargetResourceIdParameter; }

            //Add updateTargetParameters to search 
            searchParameters += targetUpdateParameters;

            foreach (Match commandMatch in commandRegEx.Matches(powershellParameters + updateTargetResourceIdParameter))
            {
                //Match match = parameterRegEx.Match(parameterLine);
                string command = commandMatch.Groups["command"].Value;
                string parameterBase = commandMatch.Groups["parameterBase"].Value;
                string parameterAttribute = commandMatch.Groups["parameterAttribute"].Value;

                if (parameterBase.StartsWith("target")) AddEventLogMessage("- Evaluate command:" + command, 4);

                switch (parameterBase.ToLower())
                {
                    case "target":
                    case "targetmodify":
                        if (!String.IsNullOrEmpty(parameterAttribute))
                        { if (!targetSearchAttributes.Contains(parameterAttribute)) targetSearchAttributes.Add(parameterAttribute); }
                        break;
                }
            }

            if (targetSearchAttributes.Count > 0 | loggingLevel > 3)
            {
                AddEventLogMessage("- Read " + targetSearchAttributes.Count.ToString() + " attribut(s) from target", 1);
                this.readResourceActivity1_SelectionAttributes1 = targetSearchAttributes.ToArray();
                foreach (String attribute in targetSearchAttributes)
                    AddEventLogMessage("  {" + attribute + "}", 3);
                AddEventLogMessage("- Read from target resource  : " + readResourceActivity1_ResourceId1.ToString(), 1);
                AddEventLogMessage("- ActorID to use for reading : " + readResourceActivity1_ActorId1.ToString(), 1);

            }

            ActionStartTime = DateTime.Now;
        }

        //Function: Add result from read target resource, includes time to execute and result
        //          And if logging level is 4 or higher all resource property information is added to log.
        private void loggReadTargetTime_ExecuteCode(object sender, EventArgs e)
        {
            TimeSpan actionTimeSpan = DateTime.Now.Subtract(ActionStartTime);
            AddEventLogMessage("- Read target resource execution time = " + actionTimeSpan.ToString(), 1);

            //If logging level is 4 or higher all resource property information is logged 
            if (loggingLevel > 3)
            {
                AddEventLogMessage(Environment.NewLine + "[Read resource property information]", 4);
                if (readResourceActivity1_Resource1 != null)
                {
                    foreach (KeyValuePair<String, ResourcePropertyInfo> item in readResourceActivity1_Resource1.ResourceProperties)
                    {
                        String temp = null;
                        if (item.Value.MaxOccurs == 1) temp += ", Single-valued";
                        else temp += ", Multi-valued";
                        if (item.Value.MinOccurs == 1) temp += ", Is required";
                        AddEventLogMessage(" {" + item.Value.Name + "}" + temp + ", " + item.Value.Type.ToString(), 4);
                    }
                }
            }
        }

        //Function: Updates the dictionary of all request attributes to be used as powershell parameters
        //          Resolves the parameters from the activitysettingspart into dependency property requestDictionary
        //
        //Input:    [RequestType]currentrequest
        //
        //Output:   [dictionary]requestDictionary
        private void resolveParameterValues_ExecuteCode(object sender, EventArgs e)
        {
            ActionStartTime = DateTime.Now;
            //String prmValue = null;

            //this.EnumerationTasks = new List<xpathEnumerationQuery>();

            RequestType currentRequest = currentRequestActivity1_CurrentRequest1;
            ReadOnlyCollection<CreateRequestParameter> requestParameters = currentRequest.ParseParameters<CreateRequestParameter>();

            AddEventLogMessage(Environment.NewLine + "[Resolve parameter attribute values]", 1);
            AddEventLogMessage("- Found " + currentRequest.RequestParameters.Count.ToString() + " requestParameters", 1);

            //Get activitysettingspart configuration for powershell unresolved parameters from dependency property 
            String allPowershellParameters = this.powershellParameters;

            //Add Update Target ActorID from configuration if specified in activitysettingspart configuraton
            if (this.ActorID_Update.ToLower().StartsWith("[//target/")) allPowershellParameters += Environment.NewLine + ActorID_Update;

            //Add all additional attribute specified by powershell parameters that is not generated by the request
            //Target values is fetched from the readResourceActivity
            //Credential is fetched from SettingsPart configuration
            foreach (Match commandMatch in commandRegEx.Matches(powershellParameters + updateTargetResourceIdParameter))
            {
                //Get parts of command
                string command = commandMatch.Groups["command"].Value;
                string parameterBase = commandMatch.Groups["parameterBase"].Value;
                string parameterAttribute = commandMatch.Groups["parameterAttribute"].Value;

                //Skip if command allready in request dictionary
                if (requestDictionary.ContainsKey(command)) { continue; }

                switch (parameterBase.ToLower())
                {
                    case "target":
                    case "targetmodify":

                        if (readResourceActivity1_Resource1[parameterAttribute] != null)
                        {
                            switch (readResourceActivity1_Resource1.ResourceProperties[parameterAttribute].MaxOccurs)
                            {
                                case 1:
                                    UpdateDictionary(command, readResourceActivity1_Resource1[parameterAttribute].ToString());
                                    break;

                                default:
                                    foreach (object value in (String)readResourceActivity1_Resource1[parameterAttribute])
                                    {
                                        UpdateDictionary(command, value.ToString());
                                    }
                                    break;
                            }
                        }
                        else
                        {
                            UpdateDictionary(command, null);
                        }
                        break;

                    case "environment":
                    case "environments":
                        UpdateDictionary(command, Environment.GetEnvironmentVariable(parameterAttribute));
                        break;
                }
            }

            //Add all resolved values to eventlog message
            foreach (KeyValuePair<String, ArrayList> key in requestDictionary)
            {
                if (key.Key == "[//Credentials/UserPassword]")
                {
                    { AddEventLogMessage(" " + key.Key.Trim('[', ']') + " {Is specified}", 2); }
                    continue;
                }
                switch (key.Value.Count)
                {
                    case 1:
                        if (key.Value[0] == null)
                        { AddEventLogMessage(" " + key.Key.Trim('[', ']') + " {Is null}", 2); }
                        else
                        { AddEventLogMessage(" " + key.Key.Trim('[', ']') + " = " + key.Value[0], 2); }
                        break;

                    default:
                        if (loggingLevel > 2)
                        {
                            foreach (String mvalue in key.Value)
                            {
                                AddEventLogMessage(" " + key.Key.Trim('[', ']') + " = " + mvalue, 3);
                            }
                        }
                        else AddEventLogMessage(" " + key.Key.Trim('[', ']') + " {contains " + key.Value.Count.ToString() + " values}", 2);
                        break;

                }
            }

            TimeSpan ActionTimeSpan = DateTime.Now.Subtract(ActionStartTime);
            AddEventLogMessage("- Resolve Parameter Values execution time = " + ActionTimeSpan.ToString(), 1);
        }

        //Function: Executes the powershell script
        //
        //Input:    [Dependency Property], from activitySettingsPart
        //          (String)powershellParameters
        //          (String)RemoteServer,UserName,UserPassword
        //          (String)executePowershellScript
        //          (Dictionary)requestDictionary
        //
        //Output:   (HashTable)resultHashTable
        //
        private void executePowershell_ExecuteCode(object sender, EventArgs e)
        {
            ActionStartTime = DateTime.Now;

            PowershellUtils myPowershellUtils = new PowershellUtils();

            RequestType currentRequest = currentRequestActivity1_CurrentRequest1;
            String parameters = powershellParameters;

            //Check if password is specified when user is specified
            if (IsValidTextLine(UserName))
            {
                if (IsValidTextLine(UserPassword)) { AddEventLogMessage("- Password is specified", 3); }
                else { AddEventLogMessage("[Warning], Password is not specified or empty", 2); }
            }

            //Open runspace for powershell
            //if remoteserver is not specified a local runspace will be crated
            Runspace myRunSpace = null;
            AddEventLogMessage(Environment.NewLine + "[Open Powershell Runspace]", 1);

            if (IsValidTextLine(RemoteServer))
            {
                try
                {
                    AddEventLogMessage("- Open remote runspace on server:" + RemoteServer + ", user:" + UserName + ", AuthMech = " + AuthenticationMechanism, 1);
                    myRunSpace = myPowershellUtils.OpenRunSpace(RemoteServer, UserName, myPowershellUtils.ConvertToSecureString(UserPassword), AuthenticationMechanism);
                }
                catch (Exception ex)
                {
                    AddEventLogMessage(ex.Message, 0);
                    WriteToEventLog_ExecuteCode(sender, e);
                    throw new Exception(ex.Message, ex.InnerException);
                }
            }
            else
            {
                AddEventLogMessage("- Remote server not specified, Open local runspace", 1);
                myRunSpace = myPowershellUtils.OpenRunSpace(null, null, null, null);
            }

            //Create Powershell
            PowerShell myPowershell = PowerShell.Create();
            myPowershell.Runspace = myRunSpace;
            AddEventLogMessage("- Runspace version : " + myRunSpace.Version.ToString(), 3);

            //add plugins to used
            if (IsValidTextLine(this.powershellCmdLetPlugins)) myPowershellUtils.AddPlugins(this.powershellCmdLetPlugins, ref myRunSpace);

            //Add CmdLet Script to execute
            myPowershell = PowerShell.Create();
            myPowershell.Runspace = myRunSpace;
            myPowershell.AddScript(executePowershellScript);

            //Add parameters to powershell command
            //Boolean strings must be converted to boolean values.
            AddEventLogMessage(Environment.NewLine + "[Add PowerShell input parameters]", 2);
            foreach (String parameterLine in powershellParameters.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
            {

                if (!IsValidTextLine(parameterLine)) continue;

                //string parameterLine = parameterMatch.Value;
                Match parameterMatch = parameterRegEx.Match(parameterLine);

                //Match match = parameterRegEx.Match(parameterLine);
                string parameterName = parameterMatch.Groups["parameterName"].Value.Trim(' ').TrimStart('-');
                string command = parameterMatch.Groups["command"].Value;
                string parameterBase = parameterMatch.Groups["parameterBase"].Value;
                string parameterAttribute = parameterMatch.Groups["parameterAttribute"].Value;
                string optionalText = trimCRLF(parameterMatch.Groups["optionalText"].Value);

                AddEventLogMessage(":Evaluate parameter:" + parameterName, 4);
                AddEventLogMessage(" Command :" + command, 4);
                if (!String.IsNullOrEmpty(optionalText)) AddEventLogMessage(" Optional Text :" + command, 4);

                ArrayList parameterValues = new ArrayList();

                if (parameterBase.ToLower().StartsWith("[xpath/")) command = "[//" + parameterBase + "/" + parameterName + "]";

                switch (command.ToLower())
                {

                    //Add boolean parameters values to powershell
                    case "[//function/boolean]":
                        myPowershell.AddParameter(parameterName, Convert.ToBoolean(optionalText));
                        AddEventLogMessage("-" + parameterName + " = " + optionalText, 2);
                        break;

                    case "[//function/text]":
                        myPowershell.AddParameter(parameterName, optionalText);
                        AddEventLogMessage("-" + parameterName + " = " + optionalText, 2);
                        break;

                    case "[//credentials/pscredential]":
                        SecureString SecurePassword = myPowershellUtils.ConvertToSecureString(PSCredentialPassword);
                        SecurePassword.MakeReadOnly();
                        PSCredential psCredential = new PSCredential(PSCredentialUserName, SecurePassword);
                        myPowershell.AddParameter(parameterName, psCredential);
                        AddEventLogMessage("-" + parameterName + " {PSCredential}", 2);
                        break;

                    case "[//credentials/UserPassword]":
                        //Add resolved value(s) from the request dictionary
                        if (requestDictionary.TryGetValue(command, out parameterValues))
                            myPowershell.AddParameter(parameterName, parameterValues[0]);
                        AddEventLogMessage("-" + parameterName + " {Is Present}", 2);
                        break;


                    //Add the rest of values
                    default:
                        //Add resolved value(s) from the request dictionary
                        if (requestDictionary.TryGetValue(command, out parameterValues))
                            if (parameterValues.Count > 1) myPowershell.AddParameter(parameterName, parameterValues.ToArray());
                            else myPowershell.AddParameter(parameterName, parameterValues[0]);
                        if (parameterValues != null)
                            if (parameterValues.Count > 1)
                            {
                                AddEventLogMessage("-" + parameterName + " contains " + parameterValues.Count.ToString() + " values", 2);
                                foreach (String item in parameterValues) AddEventLogMessage(" {" + item + "}", 3);
                            }
                            else { AddEventLogMessage("-" + parameterName + " = " + parameterValues[0], 2); }
                        break;
                }
            }

            AddEventLogMessage(Environment.NewLine + "[Execute powershell]", 1);

            //Execute powershell and get returning psObjects
            ICollection<PSObject> psObjects = null;
            string errorMsg = null;
            if (!myPowershellUtils.ExecutePowershell(myPowershell, ref psObjects, ref errorMsg, false))
            {
                AddEventLogMessage("[Error], Command failed to execute : " + errorMsg, 0);
                WriteToEventLog_ExecuteCode(sender, e);
                throw new Exception("- Powershell execution error : " + errorMsg);
            }
            else
            {
                if (myPowershell.Streams.Warning.Count > 0)
                { AddEventLogMessage("[Warning], Command executed with following warning" + myPowershell.Streams.Warning[0].Message + Environment.NewLine, 0); }
                else if (myPowershell.Streams.Error.Count > 0)
                { AddEventLogMessage("[Error], Command executed with following error" + myPowershell.Streams.Error[0].Exception.Message + Environment.NewLine, 0); }
                else AddEventLogMessage("- Sucess: Command completed successfully ", 1);
            }

            TimeSpan timeSpan = DateTime.Now.Subtract(ActionStartTime);
            AddEventLogMessage("- Powershell execution time = " + timeSpan.ToString(), 1);

            //Populate the resultHashTable from the powershell PSObjects result
            if (psObjects.Count > 0)
            {
                AddEventLogMessage("- Powershell returned " + psObjects.Count().ToString() + " PSObject", 2);
                if (psObjects.Count > 1) AddEventLogMessage("[Warning] Powershell returned " + psObjects.Count.ToString() + " Powershell Objects, only first will be used, Check powershell script syntax.", 2);

                //Return first valid psObject
                foreach (PSObject psObject in psObjects) if (resultHashTable == null)
                    {
                        if (psObject.BaseObject is Hashtable)
                        {
                            AddEventLogMessage("- Found valid psObject of HashTable type, Skip remaining objects", 2);
                            this.resultHashTable = (Hashtable)psObject.BaseObject; break;
                        }
                        else { AddEventLogMessage("{Warning}, returned object-type {" + psObject.BaseObject.ToString() + "} is not a HashTable type, Skipping object", 2); }
                    }
                if (resultHashTable != null && resultHashTable.Keys.Count > 0)
                {
                    AddEventLogMessage("- Returned " + resultHashTable.Keys.Count.ToString() + " parameters", 2);
                    foreach (String item in resultHashTable.Keys)
                    {
                        if (resultHashTable[item] != null) { AddEventLogMessage(" {" + item + "}, Type=" + resultHashTable[item].GetType().ToString(), 3); }
                        else { AddEventLogMessage(" {" + item + "}, is null type", 3); }
                    }
                }
            }
            else
            {
                resultHashTable = null;
                AddEventLogMessage("[Warning] Powershell returned no PSObject", 1);
            }
        }

        //Function: Get powershell script to execute in folowing order
        //          1. Load from activitySettings configuration if specified
        //          2. Load from file if specified and found
        //
        //Input:    PowershellCmdLetScript
        //          PowershellCmdLetFile
        //
        //Output:   executePowershellScript
        //
        private void getPowershellCmdLetScript_ExecuteCode(object sender, EventArgs e)
        {

            //Get PS script from configuration or file
            AddEventLogMessage(Environment.NewLine + "[Get PowerShell Script]", 1);
            if (IsValidTextLine(this.PowershellCmdLetScript))
            {
                AddEventLogMessage("- Reading script from activity configuration", 1);
                executePowershellScript = this.PowershellCmdLetScript;
            }
            else AddEventLogMessage("{Error}, Failed to read powershell script from either configuration or file" + Environment.NewLine + "# Check if script is defined in activity configuration or if specified file exist", 1);

            if (executePowershellScript.Contains("Write-Host"))
            {
                executePowershellScript = executePowershellScript.Replace("Write-Host", "#Write-Host");
                AddEventLogMessage("! Temporary replaced Write-Host -> #Write-Host", 3);
            }
            if (!String.IsNullOrEmpty(executePowershellScript))
                AddEventLogMessage(Environment.NewLine + "==================== Start PowerShell script ====================" + Environment.NewLine + executePowershellScript + Environment.NewLine + "===================== End PowerShell script =====================", 3);
            else
            {
                WriteToEventLog_ExecuteCode(sender, e);
                throw new Exception("PowerShell cmdlet script is not specified, exit execute PowerShell");
            }

        }

        private void initUpdateTargetActivity_ExecuteCode(object sender, EventArgs e)
        {
            RequestType currentRequest = currentRequestActivity1_CurrentRequest1;

            //updateWorkFlowDataDictionary = new Dictionary<string, ArrayList>();
            //ArrayList targetGUID = new ArrayList();

            //Add configured target update parameters
            AddEventLogMessage(Environment.NewLine + "[Init Update Target]", 2);
            if (String.IsNullOrEmpty(targetUpdateParameters))
            { AddEventLogMessage("[Warning], No update target parameters was specified, Skip update target resource", 2); }
            else
            {
                //Get parent workflow
                SequentialWorkflow containingWorkFlow = null;
                if (!SequentialWorkflow.TryGetContainingWorkflow(this, out containingWorkFlow))
                { throw new InvalidOperationException("[Error], Couldnot get parent workflow"); }

                //Resolve the resourceID to specify witch resource to update.
                Guid targetID = containingWorkFlow.TargetId;
                AddEventLogMessage(":Resolve Update Resource ID", 2);
                AddEventLogMessage("- targetID = " + targetID, 3);
                targetID = ResolveActorTargetID(updateTargetResourceIdParameter, targetID);
                updateResourceActivity1_ResourceId1 = targetID;
                AddEventLogMessage("- Resolved Update ResourceID to " + targetID.ToString(), 2);

                //Resolve the ActorID to specify under witch context the update should be performed.
                AddEventLogMessage(":Resolve Update Actor ID", 2);
                AddEventLogMessage("- UpdateTargetActorIDParameter = " + updateTargetActorID, 3);
                updateTargetActorID = containingWorkFlow.ActorId;
                updateTargetActorID = ResolveActorTargetID(ActorID_Update, updateTargetActorID);
                AddEventLogMessage("- Resolved Update ActorID to " + updateTargetActorID.ToString(), 2);
                //updateResourceActivity1_ActorId1 = updateTargetActorID;

                //List<UpdateRequestParameter> myUpdateRequestParameters = new List<UpdateRequestParameter>();
                myUpdateRequestParameters = new List<UpdateRequestParameter>();

                AddEventLogMessage(Environment.NewLine + "[Create UpdateRequestParameter and WorkFlowData update ]", 2);
                foreach (Match updateParameter in parameterLinesRegEx.Matches(targetUpdateParameters))
                {
                    String type = null;
                    if (!IsValidTextLine(updateParameter.Value)) continue;

                    //string parameterLine = parameterMatch.Value;
                    Match parameterMatch = parameterRegEx.Match(updateParameter.Value);

                    //Match match = parameterRegEx.Match(parameterLine);
                    string parameterName = parameterMatch.Groups["parameterName"].Value.Trim(' ').TrimStart('-');
                    string command = parameterMatch.Groups["command"].Value;
                    string parameterBase = parameterMatch.Groups["parameterBase"].Value;
                    string parameterAttribute = parameterMatch.Groups["parameterAttribute"].Value;
                    string optionalText = trimCRLF(parameterMatch.Groups["optionalText"].Value);

                    AddEventLogMessage(":Evaluate parameter line : " + updateParameter.Value, 4);

                    //Vaidate configured target attribute with schema
                    object entry = null;
                    if (parameterBase.ToLower().StartsWith("target") && readResourceActivity1_Resource1 != null)
                    {
                        if (!readResourceActivity1_Resource1.ResourceProperties.ContainsKey(parameterAttribute))
                        {
                            AddEventLogMessage("#Error: Target attribute " + parameterAttribute + " is missing or incorrect spelled", 2);
                            continue;
                        }
                        else
                        {
                            type = readResourceActivity1_Resource1.ResourceProperties[parameterAttribute].Type;
                        }
                    }

                    //Get the Value from the HashTable entry or continue evaluating next line
                    if (resultHashTable.ContainsKey(parameterName)) { entry = (object)resultHashTable[parameterName]; }
                    else continue;

                    //Convert entry to match target type
                    switch (type)
                    {
                        case "dateTimeType":
                            if (!(entry is DateTime))
                            {
                                AddEventLogMessage("- Converting "+ type +" value <" + entry.ToString() + "> to dateTime", 3);
                                entry = Convert.ToDateTime(entry);
                            }
                            break;

                        case "integerType":
                            if (!(entry is Int32))
                            {
                                AddEventLogMessage("- Converting " + type + " value <" + entry.ToString() + "> to int32", 3);
                                entry=Convert.ToInt32(entry);
                            }
                            break;
                        case "booleanType":
                            if (!(entry is bool))
                            {
                                AddEventLogMessage("- Converting " + type + " value <" + entry.ToString() + "> to boolean", 3);
                                entry = Convert.ToBoolean(entry);
                            }
                            break;
                        case "stringType":
                            if (!(entry is string))
                            {
                                AddEventLogMessage("- Converting " + type + " value <" + entry.ToString() + "> to string", 3);
                                entry = Convert.ToString(entry);
                            }
                            break;
                        case null:
                            AddEventLogMessage("! Null value detected", 3);
                            break;
                        default:
                            break;
                    }
                    ArrayList myValues = new ArrayList();
                    if (entry is Array) myValues.AddRange((Object[])entry);
                    else if (entry is ArrayList) myValues.AddRange((ArrayList)entry);
                    else myValues.Add(entry);

                    switch (parameterBase.ToLower())
                    {
                        //concats multivalues to singlevalue
                        case "targetconcat":
                            //Not implemented
                            break;

                        //Sets a multivalue attribute to new values and clears the old values before.
                        case "targetset":
                            myUpdateRequestParameters.Add(new UpdateRequestParameter(parameterAttribute, UpdateMode.Modify, null));
                            foreach (Object value in myValues)
                                myUpdateRequestParameters.Add(new UpdateRequestParameter(parameterAttribute, UpdateMode.Insert, value));
                            break;

                        //Create modify request, if source is multivalued the first value will be used
                        case "target":
                        case "targetmodify":
                            myUpdateRequestParameters.Add(new UpdateRequestParameter(parameterAttribute, UpdateMode.Modify, myValues[0]));
                            break;

                        //Insert values into multivalued attributes
                        case "targetinsert":
                        case "targetadd":
                            foreach (Object value in myValues)
                                myUpdateRequestParameters.Add(new UpdateRequestParameter(parameterAttribute, UpdateMode.Insert, value));
                            break;

                        //Remove values from multivalued attributes
                        case "targetremove":
                        case "targetdel":
                        case "targetdelete":
                            foreach (Object value in myValues)
                                myUpdateRequestParameters.Add(new UpdateRequestParameter(parameterAttribute, UpdateMode.Remove, value));
                            break;

                        //Add workflowdata attribute to workflow
                        case "workflowdata":

                            object currentAttributeValues = null;
                            if (containingWorkFlow.WorkflowDictionary.TryGetValue(parameterAttribute, out currentAttributeValues))
                            {
                                AddEventLogMessage("- Update existing WorkFlowData attribute : " + parameterAttribute, 2);
                                //ArrayList tempValues = new ArrayList();
                                if (currentAttributeValues is Array) myValues.AddRange((Object[])currentAttributeValues);
                                else if (currentAttributeValues is ArrayList) myValues.AddRange((ArrayList)currentAttributeValues);
                                else myValues.Add(currentAttributeValues);
                                containingWorkFlow.WorkflowDictionary.Remove(parameterAttribute);
                                containingWorkFlow.WorkflowDictionary.Add(parameterAttribute, myValues.ToArray());
                            }
                            else
                            {
                                AddEventLogMessage("- Add WorkFlowData attribute : " + parameterAttribute, 2);
                                containingWorkFlow.WorkflowDictionary.Add(parameterAttribute, myValues.ToArray());
                            }

                            foreach (Object value in myValues) AddEventLogMessage(parameterAttribute + " = " + value.ToString(), 2);
                            break;

                        default:
                            AddEventLogMessage("[Warning], Type <" + parameterBase + "> is not supported, use Target,Target,TargetInsert,TargetRemove or WorkFlowData", 2);
                            break;
                    }

                }
            }

            //Set UpdateRequestParametes on the updateResourceActivity
            if (myUpdateRequestParameters != null && myUpdateRequestParameters.Count > 0)
            {
                updateResourceActivity1_UpdateParameters1 = myUpdateRequestParameters.ToArray<UpdateRequestParameter>();
                AddEventLogMessage("- Add following UpdateRequestParameter(s)", 2);
                foreach (UpdateRequestParameter item in myUpdateRequestParameters)
                    if (item.Value != null)
                    { AddEventLogMessage("- " + item.Mode.ToString() + " " + item.Value.ToString() + " on attribute : " + item.PropertyName.ToString(), 2); }
                    else
                    { AddEventLogMessage(item.Mode.ToString() + " {null} on attribute : " + item.PropertyName.ToString(), 2); }
            }

            ActionStartTime = DateTime.Now;
        }

        private void logUpdateTargetTime_ExecuteCode(object sender, EventArgs e)
        {
            TimeSpan ActionTimeSpan = DateTime.Now.Subtract(ActionStartTime);
            AddEventLogMessage("- Update target execution time = " + ActionTimeSpan.ToString(), 1);
        }

        private void logNoUpdateTarget_ExecuteCode(object sender, EventArgs e)
        {
            TimeSpan ActionTimeSpan = DateTime.Now.Subtract(ActionStartTime);
            AddEventLogMessage("- No updates to perform on target, Skip update target", 1);
        }

        private void handleDeleteOperation_ExecuteCode(object sender, EventArgs e)
        {
            //Handle delete operations
            AddEventLogMessage(Environment.NewLine + "[Delete Operation]", 3);
            AddEventLogMessage("- Operation is not handled by this activity", 3);
        }

        private void WriteToEventLog_ExecuteCode(object sender, EventArgs e)
        {
            if (this.loggingLevel > 0)
            {
                DateTime endDate = DateTime.Now;
                TimeSpan timeSpan = endDate.Subtract(this.workFlowStartTime);

                String fullEventLogSource = eventLogSource + ", " + this.activityName;

                //Use specified eventlog other than Application
                if (!string.IsNullOrEmpty(eventLogName) && (EventLog.Exists(eventLogName)) && EventLog.SourceExists(fullEventLogSource))
                {
                    try
                    {
                        //Write message to eventlog
                        using (EventLog mylog = new EventLog(eventLogName, ".", fullEventLogSource))
                        {
                            //Register source in eventlog
                            if (!EventLog.SourceExists(fullEventLogSource)) EventLog.CreateEventSource(fullEventLogSource, eventLogName);

                            mylog.Source = fullEventLogSource;
                            mylog.WriteEntry(this.eventLogMessage, EventLogEntryType.Information, 1000);
                        }
                    }
                    catch (Exception eventEx)
                    {
                        AddEventLogMessage("Error : " + eventEx.Message, 1);
                        AddEventLogMessage("# Failed to use specified eventlog name [" + eventLogName + "] and source [" + fullEventLogSource + "], switch to default application log", 1);
                        EventLog.WriteEntry(fullEventLogSource, this.eventLogMessage, EventLogEntryType.Error, 1000);
                    }
                }
                //Use default Application eventlog
                else { EventLog.WriteEntry(fullEventLogSource, this.eventLogMessage, EventLogEntryType.Information, 1000); }
            }
        }

        private void loggNoReadResourceRequired_ExecuteCode(object sender, EventArgs e)
        {
            AddEventLogMessage("- No [//Target/*] specified in powershell parameters, Skip read resource activity because reading properties is not required", 1);
        }

        private void UpdateResourceActivityException_ExecuteCode(object sender, EventArgs e)
        {
            Exception exception = faultHandlerActivity1_Fault1;

            AddEventLogMessage("[UpdateResourceActivityException]", 0);
            AddEventLogMessage(faultHandlerActivity2_Fault1.Message, 0);
            WriteToEventLog_ExecuteCode(sender, e);
            throw new Exception(faultHandlerActivity1_Fault1.Message);
        }

        private void ReadResourceFaultHandlerActivity1_codeActivity1_ExecuteCode(object sender, EventArgs e)
        {
            AddEventLogMessage("[ReadResourceActivityException]", 0);
            AddEventLogMessage(ReadResourceFaultHandlerActivity1_Fault1.Message, 0);
            WriteToEventLog_ExecuteCode(sender, e);
            throw new Exception(ReadResourceFaultHandlerActivity1_Fault1.Message);
        }

        void ReadTarget_Closed(object sender, ActivityExecutionStatusChangedEventArgs e)
        {
            AddEventLogMessage("Activity " + e.Activity.Name + "  result", 4);
        }

        private void faultHandlersActivity3_codeActivity1_ExecuteCode(object sender, EventArgs e)
        {
            AddEventLogMessage("#Error : " + faultHandlerActivity1_Fault2.Message, 0);
            if (faultHandlerActivity1_Fault2.InnerException != null) AddEventLogMessage("#Inner Exeption : " + faultHandlerActivity1_Fault2.InnerException, 0);
        }

        private void AddCurrentRequestToParameters_ExecuteCode(object sender, EventArgs e)
        {
            ActionStartTime = DateTime.Now;
            String prmValue = null;

            //this.EnumerationTasks = new List<xpathEnumerationQuery>();

            RequestType currentRequest = currentRequestActivity1_CurrentRequest1;
            ReadOnlyCollection<CreateRequestParameter> requestParameters = currentRequest.ParseParameters<CreateRequestParameter>();

            AddEventLogMessage(Environment.NewLine + "[Add Current Request Parameters]", 1);
            AddEventLogMessage("- Found " + currentRequest.RequestParameters.Count.ToString() + " requestParameters", 1);

            //Add operation and function values to requestDictionary
            UpdateDictionary("[//Operation/Requestor]", currentRequest.Creator.ToString());
            UpdateDictionary("[//Operation/Target]", currentRequest.Target.ToString());
            UpdateDictionary("[//Operation/TargetObjectType]", currentRequest.TargetObjectType.ToString());
            UpdateDictionary("[//Operation/OperationType]", currentRequest.Operation.ToString());
            UpdateDictionary("[//Operation/CreatedTime]", currentRequest.CreatedTime.ToString());

            //Add credential values to requestDictionary
            if (!string.IsNullOrEmpty(this.UserName))
            {
                if (this.UserName.Contains('\\'))
                {
                    UpdateDictionary("[//Credentials/UserName]", this.UserName.Split('\\')[1]);
                    UpdateDictionary("[//Credentials/Domain]", this.UserName.Split('\\')[0]);
                }
                else UpdateDictionary("[//Credentials/UserName]", this.UserName);
                if (IsValidTextLine(this.UserPassword)) UpdateDictionary("[//Credentials/UserPassword]", this.UserPassword);
                else AddEventLogMessage("[Warning], Password not specified", 1);
            }

            //Add configuration values to requestDictionary
            if (IsValidTextLine(this.RemoteServer)) UpdateDictionary("[//Config/RemoteServer]", this.RemoteServer);
            UpdateDictionary("[//Config/LogLevel]", this.loggingLevel.ToString().ToString());
            if (IsValidTextLine(activityName)) { UpdateDictionary("[//Config/ActivityName]", this.activityName); }
            UpdateDictionary("[//Config/AuthenticationMechanism]", this.AuthenticationMechanism);
            if (IsValidTextLine(this.powershellCmdLetPlugins)) UpdateDictionary("[//Config/CmdLetPlugins]", this.powershellCmdLetPlugins);
            if (IsValidTextLine(this.eventLogName)) UpdateDictionary("[//Config/EventLogName]", this.eventLogName);

            //Add all attribute changes from request to requestDictionary
            switch (currentRequest.Operation)
            {
                case OperationType.Create:

                    foreach (CreateRequestParameter createRequestParameter in requestParameters)
                    {
                        if (createRequestParameter.Value != null) prmValue = createRequestParameter.Value.ToString();
                        else prmValue = null;
                        UpdateDictionary("[//RequestCreate/" + createRequestParameter.PropertyName + "]", prmValue);

                    }
                    break;

                case OperationType.Put:

                    foreach (UpdateRequestParameter updateRequestParameter in requestParameters)
                    {
                        if (updateRequestParameter.Value == null) prmValue = null;
                        else prmValue = updateRequestParameter.Value.ToString();
                        UpdateDictionary("[//Request" + updateRequestParameter.Mode.ToString() + "/" + updateRequestParameter.PropertyName + "]", prmValue);
                    }
                    break;
            }

            //Add all resolved values to eventlog message
            foreach (KeyValuePair<String, ArrayList> key in requestDictionary)
            {
                if (key.Key == "[//Credentials/UserPassword]")
                {
                    AddEventLogMessage(" " + key.Key.Trim('[', ']') + " {Is specified}", 2);
                    continue;
                }
                switch (key.Value.Count)
                {
                    case 1:
                        if (key.Value[0] == null) AddEventLogMessage(" " + key.Key.Trim('[', ']') + " {Is null}", 2);
                        else AddEventLogMessage(" " + key.Key.Trim('[', ']') + " = " + key.Value[0], 2);
                        break;

                    default:
                        if (loggingLevel > 2) { foreach (String mvalue in key.Value) AddEventLogMessage(" " + key.Key.Trim('[', ']') + " = " + mvalue, 3); }
                        else AddEventLogMessage(" " + key.Key.Trim('[', ']') + " {contains " + key.Value.Count.ToString() + " values}", 2);
                        break;

                }
            }

            TimeSpan ActionTimeSpan = DateTime.Now.Subtract(ActionStartTime);
            AddEventLogMessage("- Resolve Parameter Values execution time = " + ActionTimeSpan.ToString(), 1);

        }


    }
}
